﻿
using System;
using System.Collections.Generic;
using System.Text;

namespace HzySocket.WebSocket.Core
{
    using HzySocket.WebSocket.Interface;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using System.Net.WebSockets;
    using System.Threading;
    using System.Threading.Tasks;

    public class WebSocketSessionBase : IWebSocketSessionBase
    {
        /// <summary>
        /// 上下文连接 Id
        /// </summary>
        public virtual string SessionKey { get; set; }
        /// <summary>
        /// httpContext 上下文
        /// </summary>
        public virtual HttpContext HttpContext { get; set; }
        /// <summary>
        /// webSocket 对象
        /// </summary>
        public virtual WebSocket WebSocket { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public virtual DateTime StartTime { get; set; }
        /// <summary>
        /// 最后更新时间
        /// </summary>
        public virtual DateTime LastActiveTime { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public virtual CancellationToken GetCancellationToken { get; set; } = default(CancellationToken);
        /// <summary>
        /// 发送异常回调事件
        /// </summary>
        public virtual Action<Exception> SendExceptionCall { get; set; }
        /// <summary>
        /// 接收到的 数据信息
        /// </summary>
        public virtual string Data { get; set; }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual T GetData<T>()
        {
            if (string.IsNullOrWhiteSpace(this.Data))
            {
                return default;
            }

            return JsonConvert.DeserializeObject<T>(this.Data);
        }
        /// <summary>
        /// 发送消息 将会把信息转换为 Json 发送给客户端
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Data"></param>
        /// <returns></returns>
        public virtual async Task SendAsync<T>(T Data)
            => await this.SendAsync(JsonConvert.SerializeObject(Data));
        /// <summary>
        /// 发送一段普通的文本
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public virtual async Task SendAsync(string Data)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Data)) return;
                var segment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(Data));

                if (this.WebSocket.State == WebSocketState.Open)
                    await this.WebSocket.SendAsync(segment, WebSocketMessageType.Text, true, this.GetCancellationToken);
            }
            catch (Exception ex)
            {
                SendExceptionCall?.Invoke(ex);
            }
        }





    }
}
